<template>
  <div class="create-purchase-request">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>创建采购申请</h3>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="purchase-form"
      >
        <el-form-item label="物品名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入物品名称" />
        </el-form-item>
        
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" :precision="0" :step="1" />
        </el-form-item>
        
        <el-form-item label="预算" prop="budget">
          <el-input-number 
            v-model="form.budget" 
            :min="0" 
            :precision="2" 
            :step="100" 
            :controls="false"
          >
            <template #prepend>¥</template>
          </el-input-number>
        </el-form-item>
        
        <el-form-item label="申请理由" prop="reason">
          <el-input 
            v-model="form.reason" 
            type="textarea" 
            rows="4" 
            placeholder="请输入申请理由" 
          />
        </el-form-item>
        
        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            :action="null"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            :file-list="fileList"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传PDF格式文件，如采购报价单等
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交申请</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { createPurchaseRequest } from '@/api/purchase-request'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const fileList = ref([])
const selectedFile = ref(null)

// 表单数据
const form = reactive({
  itemName: '',
  quantity: 1,
  budget: 0,
  reason: ''
})

// 表单验证规则
const rules = {
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  budget: [
    { required: true, message: '请输入预算', trigger: 'blur' },
    { type: 'number', min: 0, message: '预算不能为负数', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请输入申请理由', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 处理文件变更
const handleFileChange = (file) => {
  // 验证文件类型
  const isPDF = file.raw.type === 'application/pdf'
  if (!isPDF) {
    ElMessage.error('只能上传PDF文件!')
    fileList.value = []
    return false
  }
  
  // 验证文件大小（小于10MB）
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    fileList.value = []
    return false
  }
  
  selectedFile.value = file.raw
  return true
}

// 处理超出文件数量限制
const handleExceed = () => {
  ElMessage.warning('只能上传一个文件')
}

// 处理移除文件
const handleRemove = () => {
  selectedFile.value = null
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await createPurchaseRequest(form, selectedFile.value)
        
        // 检查响应中是否包含邮件发送失败的警告信息
        if (response.warning && response.warning.includes('邮件发送失败')) {
          // 数据保存成功但邮件发送失败
          ElMessage({
            message: '采购申请已保存，但通知邮件发送失败，请联系管理员',
            type: 'warning',
            duration: 5000
          })
          router.push('/purchase-requests')
        } else {
          // 完全成功的情况
          ElMessage.success('采购申请提交成功')
          router.push('/purchase-requests')
        }
      } catch (error) {
        console.error('提交采购申请失败:', error)
        
        // 检查错误响应中是否包含特定信息
        if (error.response && error.response.data && error.response.data.message) {
          if (error.response.data.message.includes('邮件发送失败') && error.response.data.requestId) {
            // 数据已保存但邮件发送失败的情况
            ElMessage({
              message: '采购申请已保存，但通知邮件发送失败，请联系管理员',
              type: 'warning',
              duration: 5000
            })
            // 跳转到已创建的申请详情页
            router.push(`/purchase-requests/${error.response.data.requestId}`)
            return
          }
        }
        
        // 其他错误情况
        ElMessage.error('提交采购申请失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
      return false
    }
  })
}
</script>

<style scoped>
.create-purchase-request {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.purchase-form {
  max-width: 800px;
}
</style> 